<template>
  <div class="webrtc-player">
    <video 
      ref="videoElement"
      class="video-element"
      :controls="controls"
      :autoplay="autoplay"
      :muted="muted"
      playsinline
      webkit-playsinline
    ></video>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import srs from '@/vendors/srs.sdk.js'

// Props
const props = defineProps({
  // WebRTC 流地址
  url: {
    type: String,
    required: true
  },
  // 是否自动播放
  autoplay: {
    type: Boolean,
    default: true
  },
  // 是否显示控制条
  controls: {
    type: Boolean,
    default: true
  },
  // 是否静音
  muted: {
    type: Boolean,
    default: true
  }
})

// Emits
const emit = defineEmits(['play', 'error', 'stateChange'])

// Refs
const videoElement = ref(null)
let webrtc = null

// 播放 WebRTC 流
const playWebrtc = (videoElement, url) => {
  console.log('开始播放WebRTC，URL:', url)
  
  if (webrtc) {
    webrtc.close()
  }
  
  webrtc = new srs.SrsRtcPlayerAsync()
  videoElement.srcObject = webrtc.stream
  
  webrtc.play(url).then(function (session) {
    console.info('WebRTC播放成功', session)
    emit('play', session)
    emit('stateChange', 'playing')
  }).catch(function (reason) {
    webrtc.close()
    console.error('WebRTC播放失败', reason)
    emit('error', reason)
    emit('stateChange', 'error')
  })
}

// 播放
const play = () => {
  if (!props.url || !videoElement.value) {
    console.warn('WebRTC URL 或视频元素未准备好')
    return
  }
  
  // 确保视频元素静音（WebRTC自动播放需要）
  videoElement.value.muted = true
  videoElement.value.autoplay = true
  
  console.log('开始播放，URL:', props.url, '视频元素:', videoElement.value)
  
  // 播放
  playWebrtc(videoElement.value, props.url)
}

// 停止
const stop = () => {
  if (webrtc) {
    webrtc.close()
    webrtc = null
  }
  
  if (videoElement.value) {
    videoElement.value.srcObject = null
  }
  
  emit('stateChange', 'stopped')
}

// 监听 URL 变化
watch(() => props.url, (newUrl) => {
  if (newUrl && props.autoplay) {
    stop()
    setTimeout(() => play(), 100)
  }
})

// 暴露方法给父组件
defineExpose({
  play,
  stop
})

// 生命周期
onMounted(() => {
  // 添加视频元素的事件监听，帮助调试
  if (videoElement.value) {
    videoElement.value.addEventListener('loadedmetadata', () => {
      console.log('视频元数据已加载')
      console.log('视频尺寸:', videoElement.value.videoWidth, 'x', videoElement.value.videoHeight)
    })
    
    videoElement.value.addEventListener('loadeddata', () => {
      console.log('视频数据已加载')
    })
    
    videoElement.value.addEventListener('canplay', () => {
      console.log('视频可以播放了')
    })
    
    videoElement.value.addEventListener('playing', () => {
      console.log('视频正在播放')
    })
    
    videoElement.value.addEventListener('error', (e) => {
      console.error('视频错误:', e)
      console.error('错误详情:', videoElement.value.error)
    })
  }
  
  if (props.url && props.autoplay) {
    play()
  }
})

onUnmounted(() => {
  stop()
})
</script>

<style lang="scss" scoped>
.webrtc-player {
  width: 100%;
  height: 100%;
  background: #000;
  
  .video-element {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
</style>